<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item label="模糊搜索" prop="cname">
                        <el-input v-model="queryParams.name" placeholder="请输入" clearable @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="展示方式" prop="display">
                        <!-- <el-input v-model="queryParams.name" placeholder="请输入业务员名称" clearable @keyup.enter="handleQuery" /> -->
                        <el-select v-model="queryParams.display" placeholder="请选择" clearable filterable >
                            <el-option label="成交状态" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleClickExport"
                        >导出</el-button>
                    </el-col>
                </el-row>
            </template>
            <el-table v-loading="loading" ref="multipleTableRef" :data="customerList" highlight-current-row @current-change="handleCurrentChange" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="成交状态" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.dealStatus == '0'" :class="scope.row.dealStatus !== '0'?'status completed':'status uncompleted'">{{'从未成交' }}</span>
                        <span v-else class="status completed">{{ `${scope.row.dealIntervalDays}天` }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="客户" prop="customerName" align="center"></el-table-column>
                <el-table-column label="业务员" prop="linkName" align="center"></el-table-column>
                <el-table-column label="下次联系时间" prop="nextContactDate" align="center"></el-table-column>
                <el-table-column label="客户级别" align="center">
                    <template #default="scope">
                        <span class="level-one" v-if="scope.row.customerLevel == '1'">一级客户</span>
                        <span class="level-two" v-else-if="scope.row.customerLevel == '2'">二级客户</span>
                        <span class="level-three" v-else-if="scope.row.customerLevel == '3'">三级客户</span>
                        <span class="level-four" v-else-if="scope.row.customerLevel == '4'">四级客户</span>
                        <span class="level-five" v-else-if="scope.row.customerLevel == '5'">五级客户</span>
                    </template>
                </el-table-column>
                <el-table-column label="客户来源" align="center">
                    <template #default="scope">
                        <span>
                            {{ customer_source.filter((item:any)=>item.value == scope.row.customerSource)[0]?.label }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="地址信息" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.province + '/' + scope.row.city + '/' + scope.row.county }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="转公海时间" prop="toSeaDate" align="center">
                    <!-- <template #default="scope">
                        <span>{{ `￥${scope.row.prePayment}` }}</span>
                    </template> -->
                </el-table-column>
                <el-table-column label="转公海方式" align="center">
                    <template #default="scope">
                        {{ to_sea_method.filter((item:any)=>item.value==scope.row.toSeaMethod)[0]?.label}}
                    </template>
                </el-table-column>
                <el-table-column label="转公海原因" prop="toSeaReason" align="center"></el-table-column>
                <el-table-column label="操作" width="190" align="center">
                    <template #default="scope">
                        <div class="operation">
                            <el-tooltip content="查看跟进记录" placement="top">
                                <el-button link type="primary" :style="{fontSize:'16px'}"  icon="User" @click="handleClickFollowRecord(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="查看备注" placement="top">
                                <el-button link type="success" :style="{fontSize:'16px'}"  icon="Warning" @click="handleClickCheckRemark(scope.row)" ></el-button>
                            </el-tooltip>
                            <el-tooltip content="领取用户" placement="top">
                                <el-button link  :style="{fontSize:'16px',color:'#800080'}"  icon="CreditCard" @click="handleReceiveCustomer(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button link type="danger" :style="{fontSize:'16px'}"  icon="Delete" @click="handleClickDelete(scope.row)"></el-button>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="标注" align="center">
                    <template #default="scope">
                        <el-button v-if="scope.row.signFlag == '1'" link icon="StarFilled" :style="{color:'orange',fontSize:'30px'}" @click="handleClickMark(scope.row)"></el-button>
                        <el-button v-else link icon="Star" :style="{fontSize:'30px'}" @click="handleClickMark(scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getList" />
        </el-card>
        <checkRemark :visible="checkRemarkVisible" :data="customerData" @close="handleCloseCheckRemark"/>
        <el-dialog v-model="receiveCustomerVisible" title="领取客户" width="25%" destory-on-close>
            <el-form :model="receiveCustomerForm" ref="receiveForm">
                <el-form-item label="此客户分配给" prop="receiver">
                    <el-select v-model="receiveCustomerForm.receiver" filterable value-key="id">
                        <el-option v-for="user in roleKeyUserList" :key="user.userId" :label="user.userName" :value="user"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleSubmitReceiveCustomer">确 定</el-button>
                    <el-button @click="handleCancelReceiverCustomer">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import type { FormInstance,ElTable} from 'element-plus';
import { CustomerVO } from '@/api/sj/customer-crm/types';
import useCRMStore from '@/store/modules/crm';
import checkRemark from './components/checkRemark.vue';
import { getToSeaApi,updateSignFlagApi,getCustomerByIdApi,deleteCustomerByIdApi,exportCustomerApi, receiveCustomer } from '@/api/sj/customer-crm/index';


const queryFormRef = ref<FormInstance>();
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<CustomerVO[]>([])
const currentRow = ref();
const total = ref(0);
const loading = ref(false);
const customerList = ref<CustomerVO[]>([]);
const customerData = ref<CustomerVO>();
const receiveCustomerVisible = ref(false);
const checkRemarkVisible = ref(false);
const receiveForm = ref<FormInstance>();
const { getUserListByRoleKey } = useCRMStore();
const { roleKeyUserList } = toRefs(useCRMStore());


const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { customer_source,settlement_type, to_sea_reason, to_sea_method } = toRefs<any>(proxy?.useDict('customer_source','settlement_type','to_sea_reason','to_sea_method'));

const data = reactive({
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        display: '1'
    },
    receiveCustomerForm:{
        receiver: {
            userId: undefined,
            userName: undefined
        }
    }
});
const { queryParams, receiveCustomerForm } = toRefs(data);

const handleSelectionChange = (val: CustomerVO[]) => {
    multipleSelection.value = val;
    console.log(multipleSelection.value);
}

/** 获取公海客户列表 */
const getCustomers = async () => {
    loading.value = true;
    const { data } = await getToSeaApi(queryParams.value);
    customerList.value = data.records;
    total.value = data.total;
    loading.value = false;
};

const handleCurrentChange = (val: any) => {
    currentRow.value = val;
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 导出 */
const handleClickExport = ()=>{
    proxy?.download('/system/customerInfo/export',
        {...queryParams.value},
        `customer_${new Date().getTime()}.xlsx`
    );
};

/**点击标识按钮 */
const handleClickMark = async (row: CustomerVO)=>{
    let updateData = {
        id: row.id,
        signFlag: row.signFlag == '0'? '1':'0'
    };
    await updateSignFlagApi(updateData).then((result)=>{
        if(result.code == 200){
            getCustomers();
        }
    });
};

/**点击删除 */
const handleClickDelete = async (row: CustomerVO)=>{
    await proxy?.$modal.confirm('确认删除客户?');
    const result = await deleteCustomerByIdApi(row.id);
    if(result.code == 200){
        proxy?.$modal.msgSuccess("删除成功");
        getCustomers();
    };
};

/** 查看跟进记录 */
const handleClickFollowRecord = (row: CustomerVO)=>{
    router.push(`/guide/followRecord/${row.id}`);
};

/**查看备注 */
const handleClickCheckRemark =  async (row: CustomerVO)=>{
    await getCustomerByIdApi(row.id).then((result)=>{
        if(result.code == 200){
            customerData.value = result.data;
            checkRemarkVisible.value = true;
        };
    });
};

/** 关闭查看备注 */
const handleCloseCheckRemark = async (row: CustomerVO)=>{
    checkRemarkVisible.value = false;
};

/** 领取客户 */
const handleReceiveCustomer = async (row: CustomerVO)=>{
    await getCustomerByIdApi(row.id).then((result)=>{
        if(result.code == 200){
            customerData.value = result.data;
            receiveCustomerVisible.value = true;
        }
    });
};

const handleSubmitReceiveCustomer = async()=>{
    const submitData = {
        customerId: customerData.value?.id,
        customerName: customerData.value?.customerName,
        personName: receiveCustomerForm.value?.receiver?.userName,
        personId: receiveCustomerForm.value?.receiver?.userId
    };
    const result = await receiveCustomer(submitData);
    if(result.code == 200){
        receiveCustomerVisible.value = false;
        getCustomers();
    };
};

const handleCancelReceiverCustomer = ()=>{
    receiveCustomerVisible.value = false;
};

onMounted(()=>{
    getCustomers();
    getUserListByRoleKey('business_role');
});

const getList = async ()=>{};

</script>

<style lang="scss" scoped>
.completed{
    color: yellowgreen;
    line-height: 60px;
}
.uncompleted{
    color: orange;
    line-height: 60px;
}
.level-one,.level-two {
    color:yellowgreen
}
.level-three,.level-four{
    color: orange;
}
.level-five{
    color: red
}
.mark{
    cursor: pointer;
}

.apply{
    color: skyblue
}

.applying{
    color: orange;
}

.welfare-passed{
    color: yellowgreen;
}

.welfare-rejected{
    color: red;
}
</style>